package cn.fbs.service;

import cn.hutool.core.util.ZipUtil;
import cn.fbs.dao.dm.*;
import cn.fbs.dao.oracle.OracleTargetMapper;
import cn.fbs.enums.*;
import cn.fbs.model.*;
import cn.fbs.model.dm.OrderStatus;
import cn.fbs.model.dm.SysUser;
import cn.fbs.model.dm.UserExamine;
import cn.fbs.model.dm.UserGroup;
import cn.fbs.param.*;
import cn.fbs.util.*;
import cn.fbs.util.imageshort.FileUtil;
import cn.fbs.vo.*;
import cn.fbs.vo.CategoryAndLabelName;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.SneakyThrows;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
//import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Log
public class ImageDataService {

    @Value("${resource.locations}")
    private String resourceLocations;
    @Value(("${xml.upload.doestUrl}"))
    private String xmlUploadDoestUrl;
    @Value(("${data.upload.doestUrl}"))
    private String dataUploadDoestUrl;
    @Value(("${video.upload.doestUrl}"))
    private String videoUploadDoestUrl;
    @Value(("${image.upload.doestUrl}"))
    private String imageUploadDoestUrl;
    @Value(("${compressRatio}"))
    private Integer compressRatio;
    @Value(("${originator}"))
    private String originator;
    @Value(("${archive.url}"))
    private String archiveUrl;
    @Value(("${myServer.url}"))
    private String myServer;
    @Value(("${diskArray}"))
    private String diskArray;
    @Value(("${maxJoinNum}"))
    private int maxJoinNum;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private FixMemoMapper fixMemoMapper;
    @Autowired
    private UserExamineMapper userExamineMapper;
    @Autowired
    private DMDataInfoMapper dataInfoMapper;
    @Autowired
    private DMImageInfoMapper imageInfoMapper;
    @Autowired
    private DMVideoInfoMapper videoInfoMapper;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DMQbCategoryConnectionMapper connectionMapper;
    @Autowired
    private DMBusinessAtlasInfoMapper atlasMidTMapper;

    @Autowired
    private DMCodeCategoryTypeMapper categoryTypeMapper;


    @Autowired
    private DMNewTargetMapper targetMapper;
    @Autowired
    private OracleTargetMapper oracleTargetMapper;



    @Autowired
    private AssignService assignService;
    @Autowired
    private OrderStatusMapper orderStatusMapper;






    public Object SingleInfo(Integer dataType, Long id) {
        if (dataType.equals(MediaEnum.IMAGE.getIndex())) {
            TImageInfoVo tImageInfoVo = imageInfoMapper.SingleInfo(id);
            return tImageInfoVo;
        }
        if (dataType.equals(MediaEnum.VIDEO.getIndex())) {
            return videoInfoMapper.SingleInfo(id);
        }
        if (dataType.equals(MediaEnum.DATA.getIndex())) {
            return dataInfoMapper.SingleInfo(id);
        }
        return "没有找到对应的数据";
    }

    //    @Cacheable(value = "getTargetData")
    public Object getTargetData(ListParamsVo params) {
        /**
         * 统一参数
         */
        List<String> targetTypes = params.getList();
        String targetTypeStr = StringUtils.join(targetTypes, "','");
        targetTypeStr = "'" + targetTypeStr + "'";
        Integer dataType = params.getDataType();
        Integer pageNo = params.getPageNo();
        Integer pageSize = params.getPageSize();

        if (targetTypes == null || targetTypes.size() == 0) {
            targetTypeStr = null;
        }
        if (dataType == null) {
            return "请选择查询数据的类型";
        }
        if (pageNo == null) {
            return "请选择pageNo";
        }
        if (pageSize == null) {
            return "请选择pageSize";
        }

        String searchName = params.getSearchName();
        if (StringUtils.isNotBlank(searchName)) {
            params.setSearchName(searchName
                    .replace("%", "/%")
                    .replace("_", "/_"));
        }
        String source = params.getSource();
        if (StringUtils.isNotBlank(source)) {
            params.setSource(source
                    .replace("%", "/%")
                    .replace("_", "/_"));
        }
        String videoTitle = params.getVideoTitle();

        if (StringUtils.isNotBlank(videoTitle)) {
            params.setVideoTitle(videoTitle
                    .replace("%", "/%")
                    .replace("_", "/_"));
        }
        TargetData targetData = new TargetData();
        if (dataType.equals(MediaEnum.IMAGE.getIndex())) {
            PageHelper.startPage(pageNo, pageSize);
            List<TImageInfoVo> imageList = null;
            if (params.getFileTypeId() != null && params.getFileTypeId() != 0) {
                imageList = imageInfoMapper.selectProductByTargetTypes2(params, targetTypeStr);
            } else {
                imageList = imageInfoMapper.selectProductByTargetTypes(params, targetTypeStr);
                for (TImageInfoVo bean : imageList) {
                    Integer examine = appendExamine(params.getUserId(), bean.getId(), MediaEnum.IMAGE.getIndex());
                    bean.setExamineType(examine);
                }

            }
            PageInfo<TImageInfoVo> pageInfo = new PageInfo<>(imageList);
            targetData.setZCImageList(pageInfo);
        }
        if (dataType.equals(MediaEnum.VIDEO.getIndex())) {
            PageHelper.startPage(pageNo, pageSize);
            List<TVideoInfoVo> videoList = null;
            if (params.getFileTypeId() != null && params.getFileTypeId() != 0) {
                videoList = videoInfoMapper.selectProductByTargetTypes2(params, targetTypeStr);
            } else {
                videoList = videoInfoMapper.selectProductByTargetTypes(params, targetTypeStr);
                for (TVideoInfo bean : videoList) {
                    Integer examine = appendExamine(params.getUserId(), bean.getId(), MediaEnum.IMAGE.getIndex());
                    bean.setExamineType(examine);
                }
            }
            PageInfo<TVideoInfoVo> pageInfo = new PageInfo<>(videoList);
            targetData.setZCVideoList(pageInfo);
        }


        if (Objects.equals(MediaEnum.DATA.getIndex(), dataType)) {
            PageHelper.startPage(pageNo, pageSize);
            List<TDataInfoVo> dataInfoVoList = dataInfoMapper.selectDataByTargetTypes(params, targetTypeStr);
            for (TDataInfoVo bean : dataInfoVoList) {
                Integer examine = appendExamine(params.getUserId(), bean.getId(), MediaEnum.IMAGE.getIndex());
                bean.setExamineType(examine);
            }
            PageInfo<TDataInfoVo> pageInfo = new PageInfo<>(dataInfoVoList);
            targetData.setDataInfoList(pageInfo);
        }
        return targetData;
    }

    private Integer appendExamine(Long userId, Long messageId,Integer mediaType) {
        return userExamineMapper.getExamineType(userId,messageId,mediaType);
    }

    public List<TDataInfoVo> searchData(String targetType, String dataName) {
        return dataInfoMapper.searchData(targetType, dataName);
    }



    public String dataPreview(Long dataInfoId) {
        TDataInfo tDataInfo = dataInfoMapper.selectByPrimaryKey(dataInfoId);
        String wordUrl = tDataInfo.getFileUrl();
        wordUrl = resourceLocations + wordUrl;
        String pdfUrl = wordUrl.substring(0, wordUrl.lastIndexOf(".")) + ".pdf";
        try {
            File pdfFile = new File(pdfUrl);
            if (!pdfFile.exists()) {
                WordToPdfUtil.wordToPdf(wordUrl, pdfUrl);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.warning("文件转换出错");
        }
        return pdfUrl.replaceFirst(resourceLocations, "");
    }





    public String uploadData(UploadParam uploadParam) {
//        String fileName = generatorFileName(uploadParam.getCategoryIds());
//        uploadParam.setFileName(fileName);
        String fileName = uploadParam.getFileName();
        if (fileName.endsWith("****")) {
            String bm = String.format("%04d", Integer.parseInt(categoryTypeMapper.getSequence()));
            String replace = fileName.replace("****", bm);
            uploadParam.setFileName(replace);
        }
        String realFileUrl = uploadParam.getRealFileUrl();
        if (StringUtils.isBlank(realFileUrl)) {
            return "500,文件地址无效";
        }
        if (!new File(realFileUrl).exists()) {
            return "500,文件地址无效";
        }
        TDataInfo dataInfo = insertData(uploadParam);
//        insertAtlasMidT(uploadParam.getAtlasIds(),dataInfo.getId(),1);
        if (uploadParam.getCategoryIds() != null && uploadParam.getCategoryIds().size() > 0) {
            categoryService.insertCategory(uploadParam.getCategoryIds(), uploadParam.getOperator(), dataInfo.getId(), 1);
        }
        return "200,新增成功";
    }




    @Transactional(rollbackFor = Exception.class)
    public void updateDataInfo(DataParam uploadParam) {
        String fileName = uploadParam.getFileName();
        if (fileName.endsWith("****")) {
            String bm = String.format("%04d", Integer.parseInt(categoryTypeMapper.getSequence()));
            String replace = fileName.replace("****", bm);
            uploadParam.setFileName(replace);
        }
        TDataInfo dataInfo = new TDataInfo();
        BeanUtils.copyProperties(uploadParam, dataInfo);
        dataInfo.setUpdateDate(new Date());
        File file = null;
        if (StringUtils.isNotBlank(uploadParam.getRealFileUrl())) {
            file = new File(uploadParam.getRealFileUrl());
        }
        if (file != null && file.exists()) {
            assignService.giveDataInfo(uploadParam, dataInfo);
        }
        dataInfoMapper.updateByPrimaryKeySelective(dataInfo);
        /**
         * 处理标签信息-删除原有标签，添加新标签
         */
        // 2021/3/15 可以优化一下--判断是否有重复的，如果有重复的数据，就将重复数据剔除
        /*
        没有必要，数据插入速度相比查询和删除要快-删除和查询速度区别不大
         */
        if (uploadParam.getCategoryIds() != null) {
            connectionMapper.deleteByMessageId(uploadParam.getId());
            if (uploadParam.getCategoryIds().size() > 0) {
                categoryService.insertCategory(uploadParam.getCategoryIds(), uploadParam.getOperator(), dataInfo.getId(), 1);
            }
        }
    }





    private TDataInfo insertData(UploadParam uploadParam) {
        TDataInfo dataInfo = new TDataInfo();
        String realFileUrl = uploadParam.getRealFileUrl();
        BeanUtils.copyProperties(uploadParam, dataInfo);
        /**
         * 赋予资料文档媒体属性
         */
        assignService.giveDataInfo(uploadParam, dataInfo);
        /**
         * 初始化信息
         */
        dataInfo.setCreateDate(new Date());
        dataInfo.setViewNumber(0L);
        dataInfo.setDownloads(0L);
//        dataInfo.setIsExamine(1);
        dataInfoMapper.insert(dataInfo);
        if (StringUtils.isNotBlank(dataInfo.getThumbnail())) {
            TDataInfo dataInfo2 = new TDataInfo();
            dataInfo2.setId(dataInfo.getId());
            dataInfo2.setThumbnail(dataInfo.getThumbnail());
            dataInfoMapper.updateByPrimaryKeySelective(dataInfo2);
        }
        return dataInfo;
    }
















    private void saveElement(Element ListElement, Class clz, String xmlDirPath) {
        List<Element> dataInfo2Elements = ListElement.elements();
        for (Element dataInfoElement : dataInfo2Elements) {
            HashMap<String, Object> map = new HashMap<>();
            List<Element> elements = dataInfoElement.elements();
            if (elements.size() == 0) {
                System.out.println("saveElement_1");
                continue;
            }
            for (Element element : elements) {
                map.put(element.getName(), element.getText());
            }
            Object object = JSON.parseObject(JSON.toJSONString(map), clz);
            if (object instanceof TDataInfo) {
                TDataInfo dataInfo = (TDataInfo) object;
                String fileUrl = dataInfo.getFileUrl();
                copyFile(fileUrl, dataUploadDoestUrl, xmlDirPath);
                dataInfoMapper.insertSelective(dataInfo);
            }
            if (object instanceof TVideoInfo) {
                TVideoInfo videoInfo = (TVideoInfo) object;
                String fileUrl = videoInfo.getFileUrl();
                copyFile(fileUrl, videoUploadDoestUrl, xmlDirPath);
                videoInfoMapper.insertSelective(videoInfo);
            }
            if (object instanceof TImageInfo) {
                TImageInfo imageInfo = (TImageInfo) object;
                String fileUrl = imageInfo.getFileUrl();
                copyFile(fileUrl, imageUploadDoestUrl, xmlDirPath);
                imageInfoMapper.insertSelective(imageInfo);
            }
        }

    }

    private void copyFile(String fileUrl, String prePath, String xmlDirPath) {
        String realFileName = fileUrl.substring(fileUrl.lastIndexOf("/"));
        String newFilePath = imageUploadDoestUrl + realFileName;
        cn.hutool.core.io.FileUtil.copy(xmlDirPath + realFileName, newFilePath, true);
    }


    private void insertAtlasMidT(List<Long> atlasIds, Long messageId, Integer type) {
        for (Long atlasId : atlasIds) {
            TBusinessAtlasInfo AtlasMidT = new TBusinessAtlasInfo();
            AtlasMidT.setAtlasId(atlasId);
            AtlasMidT.setMessageId(messageId);
            AtlasMidT.setConnectionType(type);
            atlasMidTMapper.insert(AtlasMidT);
        }

    }


    @Transactional(rollbackFor = Exception.class)
    public void deleteData(DeleteParam params) {
        List<Long> ids = params.getIds();
        String idsStr = StringUtils.join(ids, ",");
        String type = params.getType();
        /**
         * 删除主表信息和关联表信息
         */
        switch (type) {
            case "image":
                /**
                 * 先删除物理文件
                 */
                List<Object> images = imageInfoMapper.selectByIdsStr(idsStr);
                if (images == null || images.size() == 0) {
                    return;
                }
                deleteFileByObjects(images);
                imageInfoMapper.deleteByIds(idsStr);
                connectionMapper.deleteByMessageIds(idsStr, 2);
                break;
            case "video":
                /**
                 * 先删除物理文件
                 */
                List<Object> videos = videoInfoMapper.selectByIdsStr(idsStr);
                if (videos == null || videos.size() == 0) {
                    return;
                }
                deleteFileByObjects(videos);
                videoInfoMapper.deleteByIds(idsStr);
                connectionMapper.deleteByMessageIds(idsStr, 3);
                break;
            case "data":
                List<Object> datas = dataInfoMapper.selectByIdsStr(idsStr);
                System.out.println("deleteData_7");
                if (datas == null || datas.size() == 0) {
                    return;
                }
                deleteFileByObjects(datas);
                dataInfoMapper.deleteByIdS(idsStr);
                connectionMapper.deleteByMessageIds(idsStr, 1);
                break;

        }


    }

    private void deleteFileByObjects(List<Object> objects) {
        for (Object object : objects) {
            Map map = JSON.parseObject(JSON.toJSONString(object), Map.class);
            String fileUrl = map.get("fileUrl").toString();
            int i = countStr(fileUrl, "/");
            if (i>3){
                fileUrl = resourceLocations + fileUrl;
                cn.hutool.core.io.FileUtil.del(fileUrl);
            }else {
                fileUrl = resourceLocations + fileUrl;
                String dirUrl = fileUrl.substring(0, fileUrl.lastIndexOf("/"));
                cn.hutool.core.io.FileUtil.del(dirUrl);
            }
        }
    }

    /**
     * 判断str1中包含str2的个数
     * @return counter
     */
    public int countStr(String SourceStr,String contain){
        SourceStr = SourceStr.replace(" ", "");
        String  targetStr= SourceStr.replace(contain, "");
        return SourceStr.length()-targetStr.length();
    }






    public Result shareVideo(List<Long> ids) throws IOException {
        Result result = new Result();
        /**
         * 同步流程
         * 1.拿到原始数据
         * 2.将原始数据写入到xml中
         * 3.调用三方接口，将xml信息交给三方接口
         */
        String baseUrl=diskArray+System.currentTimeMillis()+"/";

        String idsStr = StringUtils.join(ids, ",");
        /**
         * 需要新写一个sql
         * 需要的信息
         * 标签，标签组，目标mc,目标上级id,文件信息
         */
        List<ShareVideoVo> imageList = videoInfoMapper.getShareVideoData(idsStr);

        /**
         * 为targetType赋值
         */

        if (imageList == null && imageList.size() == 0) {
            result.setCode(500);
            result.setMsg("未找到同步数据");
            return result;
        }
        Document document = DocumentHelper.createDocument();
        Element rootElement = document.addElement("Root");
        for (ShareVideoVo infoVo : imageList) {
            System.out.println("shareVideo_2");
            Element beanElement = rootElement.addElement("Object");
            /**
             * 将图像文件放到共享目录中
             */
            String srcPath=resourceLocations + new File(infoVo.getFileUrl());
            String destPath=baseUrl+infoVo.getUploadFileName();
            cn.hutool.core.io.FileUtil.copy(srcPath,destPath,true);
            /**
             * 赋予可以直接取到的数据
             */
            assignmentField(beanElement, infoVo);
            /**
             * 赋予属于标签的数据
             */
            assignmentCategory(beanElement,infoVo);
        }
        /**
         * 将xml写出
         */
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setEncoding("UTF-8");
        String xmlPath=baseUrl+System.currentTimeMillis()+".xml";
        FileOutputStream fileOutputStream = new FileOutputStream(xmlPath);
        XMLWriter xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
        xmlWriter.write(document);
        xmlWriter.close();
        fileOutputStream.close();

        /**
         * 调用三方接口
         */
        return transferApi(xmlPath);
    }
    public Result shareImage(List<Long> ids) throws IOException {
        Result result = new Result();
        /**
         * 同步流程
         * 1.拿到原始数据
         * 2.将原始数据写入到xml中
         * 3.调用三方接口，将xml信息交给三方接口
         */
        String baseUrl=diskArray+System.currentTimeMillis()+"/";

        String idsStr = StringUtils.join(ids, ",");
        /**
         * 需要新写一个sql
         * 需要的信息
         * 标签，标签组，目标mc,目标上级id,文件信息
         */
        List<ShareImageVo> imageList = imageInfoMapper.getShareImageData(idsStr);

        /**
         * 为targetType赋值
         */

        if (imageList == null && imageList.size() == 0) {
            result.setMsg("未找到同步数据");
            result.setCode(500);
            return result;
        }
        Document document = DocumentHelper.createDocument();
        Element rootElement = document.addElement("Root");
        for (ShareImageVo infoVo : imageList) {

            Element beanElement = rootElement.addElement("Object");
            /**
             * 将图像文件放到共享目录中
             */
            String srcPath=resourceLocations + new File(infoVo.getFileUrl());
            String destPath=baseUrl+infoVo.getUploadFileName();
            cn.hutool.core.io.FileUtil.copy(srcPath,destPath,true);
            /**
             * 赋予可以直接取到的数据
             */
            assignmentField(beanElement, infoVo);
            /**
             * 赋予属于标签的数据
             */
            assignmentCategory(beanElement,infoVo);
        }
        /**
         * 将xml写出
         */
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setEncoding("UTF-8");
        String xmlPath=baseUrl+System.currentTimeMillis()+".xml";
        FileOutputStream fileOutputStream = new FileOutputStream(xmlPath);
        XMLWriter xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
        xmlWriter.write(document);
        xmlWriter.close();


        /**
         * 调用三方接口
         */
        return transferApi(xmlPath);

    }


    private Result transferApi(String xmlPath) {

        /**
         *构造接口参数
         */
        JSONObject jsonObject = new JSONObject();
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        jsonObject.put("taskId",format.format(date));
        jsonObject.put("path",xmlPath);
        jsonObject.put("type","14");
        jsonObject.put("originator",originator);
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        jsonObject.put("taskTime",format2.format(date));
//        RestTemplate restTemplate = new RestTemplate();
        System.out.println(jsonObject.toJSONString());
        Result result = new Result();
        Object resultObj;
        try {
            resultObj= restTemplate.postForObject(archiveUrl, jsonObject, Object.class);
            result = parseResult(resultObj);

        }catch (Exception e){
            result.setCode(500);
            result.setMsg("共享信息提交失败");
        }
        return result;
    }

    private Result parseResult(Object resultObj) throws InterruptedException {
        Result result = new Result();
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(resultObj);
        System.out.println(jsonObject.toString());

        Object status = jsonObject.get("status");
        if (status!=null&& "0".equals(status.toString())){
            /**
             * 若用户接收消息成功，则每２秒查询一次数据库，判断是否有回调，若有，则退出循环，若无，则判断失败
             */
            String orderIdStr = jsonObject.get("reason").toString();
            String orderId = orderIdStr.replace("订单号：", "");
            for (int i = 0; i < 30; i++) {
                Thread.sleep(2000);
                List<OrderStatus> list=orderStatusMapper.getByOrderId(orderId);
                if (list!=null&&list.size()>0){
                    OrderStatus orderStatus = list.get(0);
                    if (orderStatus.getStatus().equalsIgnoreCase("0")){
                        result.setCode(200);
                        result.setMsg("共享信息提交成功");
                    }
                    if (orderStatus.getStatus().equalsIgnoreCase("1")){
                        result.setCode(200);
                        result.setMsg("共享信息提交成功,信息接收方执行失败");
                    }
                    break;
                }

            }
            if (result.getCode()!=null){
                return result;
            }
        }
        result.setMsg("共享信息提交失败");
        result.setCode(500);
        System.out.println(result);
        return result;
    }

    private void assignmentCategory(Element beanElement, Object object) {

        if (object instanceof ShareImageVo) {
            System.out.println("assignmentCategory_1");
            ShareImageVo infoVo = (ShareImageVo) object;
            HashMap<String, CategoryAndLabelName> map = new HashMap<>();
            List<CategoryAndLabelName> categoryTypeList = infoVo.getCategoryTypeList();
            for (CategoryAndLabelName categoryAndLabelName : categoryTypeList) {
                map.put(categoryAndLabelName.getLabelName(), categoryAndLabelName);
            }

            if (map.get(FileNameEnum.FILETYPE.getName()) != null) {
                System.out.println("assignmentCategory_2");
                beanElement.addElement(XmlFieldEnum.FILE_TYPE.getName()).setText(map.get(FileNameEnum.FILETYPE.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_3");
                beanElement.addElement(XmlFieldEnum.FILE_TYPE.getName()).setText("");
            }
            if (map.get(FileNameEnum.COUNTRY.getName()) != null) {
                System.out.println("assignmentCategory_4");
                beanElement.addElement(XmlFieldEnum.COUNTRY.getName()).setText(map.get(FileNameEnum.COUNTRY.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_5");
                beanElement.addElement(XmlFieldEnum.COUNTRY.getName()).setText("");
            }
            if (map.get(FileNameEnum.STATUS.getName()) != null) {
                System.out.println("assignmentCategory_6");
                beanElement.addElement(XmlFieldEnum.STATUS.getName()).setText(map.get(FileNameEnum.STATUS.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_7");
                beanElement.addElement(XmlFieldEnum.STATUS.getName()).setText("");
            }

            if (map.get(FileNameEnum.POSITION.getName()) != null) {
                System.out.println("assignmentCategory_8");
                beanElement.addElement(XmlFieldEnum.POSITION.getName()).setText(map.get(FileNameEnum.POSITION.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_9");
                beanElement.addElement(XmlFieldEnum.POSITION.getName()).setText("");
            }

            if (map.get(FileNameEnum.LOCATION.getName()) != null) {
                System.out.println("assignmentCategory_10");
                beanElement.addElement(XmlFieldEnum.LOCATION.getName()).setText(map.get(FileNameEnum.LOCATION.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_11");
                beanElement.addElement(XmlFieldEnum.LOCATION.getName()).setText("");
            }

            if (map.get(FileNameEnum.AREA.getName()) != null) {
                System.out.println("assignmentCategory_12");
                beanElement.addElement(XmlFieldEnum.AREA.getName()).setText(map.get(FileNameEnum.AREA.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_13");
                beanElement.addElement(XmlFieldEnum.AREA.getName()).setText("");
            }

            if (map.get(FileNameEnum.DISTANCE.getName()) != null) {
                System.out.println("assignmentCategory_14");
                beanElement.addElement(XmlFieldEnum.DISTANCE.getName()).setText(map.get(FileNameEnum.DISTANCE.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_15");
                beanElement.addElement(XmlFieldEnum.DISTANCE.getName()).setText("");
            }

            if (map.get(FileNameEnum.CLEAR.getName()) != null) {
                System.out.println("assignmentCategory_16");
                beanElement.addElement(XmlFieldEnum.CLEAR.getName()).setText(map.get(FileNameEnum.CLEAR.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_17");
                beanElement.addElement(XmlFieldEnum.CLEAR.getName()).setText("");
            }
        }
        if (object instanceof ShareVideoVo) {
            ShareVideoVo infoVo = (ShareVideoVo) object;
            HashMap<String, CategoryAndLabelName> map = new HashMap<>();
            List<CategoryAndLabelName> categoryTypeList = infoVo.getCategoryTypeList();
            for (CategoryAndLabelName categoryAndLabelName : categoryTypeList) {
                System.out.println("assignmentCategory_18");
                map.put(categoryAndLabelName.getLabelName(), categoryAndLabelName);
            }

            if (map.get(FileNameEnum.FILETYPE.getName()) != null) {
                System.out.println("assignmentCategory_19");
                beanElement.addElement(XmlFieldEnum.FILE_TYPE.getName()).setText(map.get(FileNameEnum.FILETYPE.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_20");
                beanElement.addElement(XmlFieldEnum.FILE_TYPE.getName()).setText("");
            }
            if (map.get(FileNameEnum.COUNTRY.getName()) != null) {
                System.out.println("assignmentCategory_21");
                beanElement.addElement(XmlFieldEnum.COUNTRY.getName()).setText(map.get(FileNameEnum.COUNTRY.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_22");
                beanElement.addElement(XmlFieldEnum.COUNTRY.getName()).setText("");
            }
            if (map.get(FileNameEnum.STATUS.getName()) != null) {
                System.out.println("assignmentCategory_23");
                beanElement.addElement(XmlFieldEnum.STATUS.getName()).setText(map.get(FileNameEnum.STATUS.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_24");
                beanElement.addElement(XmlFieldEnum.STATUS.getName()).setText("");
            }

            if (map.get(FileNameEnum.POSITION.getName()) != null) {
                System.out.println("assignmentCategory_25");
                beanElement.addElement(XmlFieldEnum.POSITION.getName()).setText(map.get(FileNameEnum.POSITION.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_26");
                beanElement.addElement(XmlFieldEnum.POSITION.getName()).setText("");
            }

            if (map.get(FileNameEnum.LOCATION.getName()) != null) {
                System.out.println("assignmentCategory_27");
                beanElement.addElement(XmlFieldEnum.LOCATION.getName()).setText(map.get(FileNameEnum.LOCATION.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_28");
                beanElement.addElement(XmlFieldEnum.LOCATION.getName()).setText("");
            }

            if (map.get(FileNameEnum.AREA.getName()) != null) {
                System.out.println("assignmentCategory_29");
                beanElement.addElement(XmlFieldEnum.AREA.getName()).setText(map.get(FileNameEnum.AREA.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_30");
                beanElement.addElement(XmlFieldEnum.AREA.getName()).setText("");
            }

            if (map.get(FileNameEnum.DISTANCE.getName()) != null) {
                System.out.println("assignmentCategory_31");
                beanElement.addElement(XmlFieldEnum.DISTANCE.getName()).setText(map.get(FileNameEnum.DISTANCE.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_32");
                beanElement.addElement(XmlFieldEnum.DISTANCE.getName()).setText("");
            }

            if (map.get(FileNameEnum.CLEAR.getName()) != null) {
                System.out.println("assignmentCategory_33");
                beanElement.addElement(XmlFieldEnum.CLEAR.getName()).setText(map.get(FileNameEnum.CLEAR.getName()).getCategoryName());
            } else {
                System.out.println("assignmentCategory_34end");
                beanElement.addElement(XmlFieldEnum.CLEAR.getName()).setText("");
            }
        }


    }

    private void assignmentField(Element beanElement, Object object) {
        if (object instanceof ShareImageVo) {
            System.out.println("assignmentField_1");
            ShareImageVo infoVo = (ShareImageVo) object;
            if (infoVo.getFileName() != null) {
                System.out.println("assignmentField_2");
                beanElement.addElement(XmlFieldEnum.FILE_NAME.name()).setText(infoVo.getFileName());
            } else {
                System.out.println("assignmentField_3");
                beanElement.addElement(XmlFieldEnum.FILE_NAME.name()).setText("");
            }
            if (infoVo.getZzdx() != null) {
                System.out.println("assignmentField_4");
                beanElement.addElement(XmlFieldEnum.TARGET_NAME.name()).setText(infoVo.getZzdx());
            } else {
                System.out.println("assignmentField_5");
                beanElement.addElement(XmlFieldEnum.TARGET_NAME.name()).setText("");
            }
            if (infoVo.getTargetType() != null) {
                System.out.println("assignmentField_6");
                beanElement.addElement(XmlFieldEnum.TARGET_TYPE.name()).setText(infoVo.getTargetType());
            } else {
                System.out.println("assignmentField_7");
                beanElement.addElement(XmlFieldEnum.TARGET_TYPE.name()).setText("");
            }
            if (infoVo.getShotDate() != null) {
                System.out.println("assignmentField_8");
                Date shotDate = infoVo.getShotDate();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                beanElement.addElement(XmlFieldEnum.SHOT_DATE.name()).setText(format.format(shotDate));
            } else {
                System.out.println("assignmentField_9");
                beanElement.addElement(XmlFieldEnum.SHOT_DATE.name()).setText("");
            }
            if (infoVo.getPlatformName() != null) {
                System.out.println("assignmentField_10");
                beanElement.addElement(XmlFieldEnum.SHOT_PLATFORM.name()).setText(infoVo.getPlatformName());
            } else {
                System.out.println("assignmentField_11");
                beanElement.addElement(XmlFieldEnum.SHOT_PLATFORM.name()).setText("");
            }
            if (infoVo.getLongitude() != null) {
                System.out.println("assignmentField_12");
                beanElement.addElement(XmlFieldEnum.LONGITUDE.name()).setText(infoVo.getLongitude());
            } else {
                System.out.println("assignmentField_13");
                beanElement.addElement(XmlFieldEnum.LONGITUDE.name()).setText("");
            }
            if (infoVo.getLatitude() != null) {
                System.out.println("assignmentField_14");
                beanElement.addElement(XmlFieldEnum.LATITUDE.name()).setText(infoVo.getLatitude());
            } else {
                System.out.println("assignmentField_15");
                beanElement.addElement(XmlFieldEnum.LATITUDE.name()).setText("");
            }
        }
        if (object instanceof ShareVideoVo) {
            System.out.println("assignmentField_16");
            ShareVideoVo infoVo = (ShareVideoVo) object;
            if (infoVo.getFileName() != null) {
                System.out.println("assignmentField_17");
                beanElement.addElement(XmlFieldEnum.FILE_NAME.name()).setText(infoVo.getFileName());
            } else {
                System.out.println("assignmentField_18");
                beanElement.addElement(XmlFieldEnum.FILE_NAME.name()).setText("");
            }
            if (infoVo.getZzdx() != null) {
                System.out.println("assignmentField_19");
                beanElement.addElement(XmlFieldEnum.TARGET_NAME.name()).setText(infoVo.getZzdx());
            } else {
                System.out.println("assignmentField_20");
                beanElement.addElement(XmlFieldEnum.TARGET_NAME.name()).setText("");
            }
            if (infoVo.getTargetType() != null) {
                System.out.println("assignmentField_21");
                beanElement.addElement(XmlFieldEnum.TARGET_TYPE.name()).setText(infoVo.getTargetType());
            } else {
                System.out.println("assignmentField_22");
                beanElement.addElement(XmlFieldEnum.TARGET_TYPE.name()).setText("");
            }
            if (infoVo.getPlatformName() != null) {
                System.out.println("assignmentField_23");
                beanElement.addElement(XmlFieldEnum.SHOT_PLATFORM.name()).setText(infoVo.getPlatformName());
            } else {
                System.out.println("assignmentField_24");
                beanElement.addElement(XmlFieldEnum.SHOT_PLATFORM.name()).setText("");
            }
            if (infoVo.getLongitude() != null) {
                System.out.println("assignmentField_25");
                beanElement.addElement(XmlFieldEnum.LONGITUDE.name()).setText(infoVo.getLongitude());
            } else {
                System.out.println("assignmentField_26");
                beanElement.addElement(XmlFieldEnum.LONGITUDE.name()).setText("");
            }
            if (infoVo.getLatitude() != null) {
                System.out.println("assignmentField_27");
                beanElement.addElement(XmlFieldEnum.LATITUDE.name()).setText(infoVo.getLatitude());
            } else {
                System.out.println("assignmentField_27end");
                beanElement.addElement(XmlFieldEnum.LATITUDE.name()).setText("");
            }

        }

    }


//        if (param.getDataType().intValue() == MediaEnum.VIDEO.getIndex().intValue()) {
//
//        }

    public String shareZCData(ShareParam param) throws IOException {
        /**
         *获取原始数据
         */
        List<Long> dataIds = param.getDataIds();
        List<Long> videoIds = param.getVideoIds();
        List<Long> imageIds = param.getImageIds();
        List<Object> dataInfoList = null;
        List<Object> videoInfoList = null;
        List<Object> imageInfoList = null;
        if (dataIds != null && dataIds.size() > 0) {
            String dataIdsStr = StringUtils.join(dataIds, ",");
            dataInfoList = dataInfoMapper.selectByIdsStr(dataIdsStr);
        }
        if (videoIds != null && videoIds.size() > 0) {
            String videoIdsStr = StringUtils.join(videoIds, ",");
            videoInfoList = videoInfoMapper.selectByIdsStr(videoIdsStr);
        }
        if (imageIds != null && imageIds.size() > 0) {
            String imageIdsStr = StringUtils.join(imageIds, ",");
            imageInfoList = imageInfoMapper.selectByIdsStr(imageIdsStr);
        }


        Document document = DocumentHelper.createDocument();
        /**
         * 创建xml并添加根节点和三个list节点
         */
        Element rootElement = document.addElement("root");
        Element dataInfosElement = rootElement.addElement("dataInfoList");
        Element videoInfosElement = rootElement.addElement("videoInfoList");
        Element imageInfosElement = rootElement.addElement("imageInfoList");

        /**
         * 将集合下的子节点数据写入到父元素中
         */
        String xmlPath = resourceLocations + "extract" + "/" + System.currentTimeMillis();
        File xmlFile = new File(xmlPath);
        xmlFile.mkdir();
        String xmlName = "资源分享.xml";
        String documentUrl = xmlPath + "/" + xmlName;
        if (dataInfoList != null) {
            insertSubElement(dataInfosElement, dataInfoList, xmlPath);
        }
        if (imageInfoList != null) {
            insertSubElement(imageInfosElement, imageInfoList, xmlPath);
        }
        if (videoInfoList != null) {
            insertSubElement(videoInfosElement, videoInfoList, xmlPath);
        }

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        File file = new File(documentUrl);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        XMLWriter xmlWriter = new XMLWriter(fileOutputStream, format);
        fileOutputStream.close();
        xmlWriter.setEscapeText(false);
        xmlWriter.write(document);
        xmlWriter.close();
        File zip = ZipUtil.zip(xmlFile);
        String path = zip.getPath();
        return path.substring(path.indexOf(resourceLocations) + resourceLocations.length());
    }

    private void insertSubElement(Element listElement, List<Object> dataInfoList, String xmlPath) {
        for (Object bean : dataInfoList) {
            Map map = JSON.parseObject(JSON.toJSONString(bean), Map.class);
            Element dataInfoElement = listElement.addElement("dataInfo");
            String sourceFilePath = resourceLocations + map.get("fileUrl").toString();
            String fileUrl = map.get("fileUrl").toString();
            if (!fileUrl.contains("/")) {
                System.out.println("insertSubElement_1");
                continue;
            }
            String realFileName = fileUrl.substring(fileUrl.lastIndexOf("/"));
            String newFilePath = xmlPath + realFileName;
            cn.hutool.core.io.FileUtil.copy(sourceFilePath, newFilePath, true);
            Set<String> keySet = map.keySet();
            dataInfoElement.setAttributeValue("id", map.get("id").toString());
            map.remove("id");
            System.out.println("insertSubElement_2");
            for (String key : keySet) {
                System.out.println("insertSubElement_3end");
                dataInfoElement.addElement(key).setText(map.get(key).toString());
            }
        }

    }

    public String generatorFileName(List<Long> categoryIds, String zzdx, Integer dataType) {
        if (categoryIds == null || categoryIds.size() == 0) {
            System.out.println("generatorFileName_1");
            return "500,请选择标签";
        }
        String idStr = StringUtils.join(categoryIds, ",");
        List<CategoryAndLabelName> list = categoryTypeMapper.queryByIdStr(idStr);
        HashMap<String, CategoryAndLabelName> voMap = new HashMap<>();
        for (CategoryAndLabelName categoryAndLabelName : list) {
            System.out.println("generatorFileName_2");
            voMap.put(categoryAndLabelName.getLabelName(), categoryAndLabelName);
        }
        ArrayList<String> strList = new ArrayList<>();
        for (FileNameEnum fileNameEnum : FileNameEnum.values()) {
            System.out.println("generatorFileName_3");
            if (!voMap.containsKey(fileNameEnum.getName())) {
                System.out.println("generatorFileName_4");
                return "500,请选择" + fileNameEnum.getName() + "标签";
            }

        }

        for (FileNameEnum fileNameEnum : FileNameEnum.values()) {
            System.out.println("generatorFileName_5");
            if (fileNameEnum.getIndex() == 1) {
                System.out.println("generatorFileName_6");
                String categoryName = voMap.get(fileNameEnum.getName()).getCategoryName();
                Integer typeNum = getTypeNum(categoryName);
                strList.add(typeNum.toString());
            } else {
                System.out.println("generatorFileName_7");
                strList.add(voMap.get(fileNameEnum.getName()).getCategoryName());
            }
        }
        if (StringUtils.isNotBlank(zzdx)) {
            System.out.println("generatorFileName_8");
            strList.add(3 - 1, zzdx);
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String DateStr = dateFormat.format(new Date());
        /**
         * 编码在插入的时候再进行赋值
         */
        String bm = "";
        if (dataType == 1) {
            System.out.println("generatorFileName_9");
            bm = String.format("%04d", Integer.parseInt(categoryTypeMapper.getSequence()));
        }
        if (dataType == 2) {
            System.out.println("generatorFileName_10");
            bm = "****";
        }
        strList.add(DateStr + bm);
        System.out.println("generatorFileName_11end");
        return StringUtils.join(strList, "_");


    }

    private Integer getTypeNum(String type) {
        int typeNum;
        switch (type) {
            case "可见光图像文件":
                System.out.println("getTypeNum_1");
                typeNum = 0;
                break;
            case "可见光影像文件":
                typeNum = 1;
                System.out.println("getTypeNum_2");
                break;
            case "红外图像文件":
                typeNum = 2;
                System.out.println("getTypeNum_3");
                break;
            case "红外影像文件":
                typeNum = 3;
                System.out.println("getTypeNum_4");
                break;
            case "微光图像文件":
                typeNum = 4;
                System.out.println("getTypeNum_5");
                break;
            case "微光影像文件":
                typeNum = 5;
                System.out.println("getTypeNum_6");
                break;
            case "合成孔径雷达图像文件":
                typeNum = 6;
                System.out.println("getTypeNum_7");
                break;
            case "音频情报文件":
                typeNum = 7;
                System.out.println("getTypeNum_8");
                break;
            case "声明影像文件":
                typeNum = 8;
                System.out.println("getTypeNum_9");
                break;
            default:
                System.out.println("getTypeNum_10");
                typeNum = -1;
        }
        System.out.println("getTypeNum_11end");
        return typeNum;
    }

    public String targetJoinData(targetJoinDataParam param) {
        Integer dataType = param.getDataType();
        if (dataType == null) {
            System.out.println("targetJoinData_1");
            return "请输入正确的数据类型";
        }
        Long id = param.getId();
        if (id == null) {
            System.out.println("targetJoinData_2");
            return "请输入id";
        }
        String zbnm = param.getZbnm();
        if (StringUtils.isBlank(zbnm)) {
            System.out.println("targetJoinData_3");
            return "请输入zbnm";
        }
        //查詢此目標对应序号条数
        /**
         * 根据zbnm查出对应的名称
         */
        NewTCodeTargetType bean = targetMapper.getByNm(zbnm);
        if (dataType.equals(MediaEnum.VIDEO.getIndex())) {
            System.out.println("targetJoinData_4");
            if (videoInfoMapper.selectCountBytargetXh(param.getZbnm(), param.getId()) > maxJoinNum) {
                return "400,目标关联数据超过最大限制!";
            }
            TVideoInfo videoInfo = new TVideoInfo();
            videoInfo.setId(id);
            videoInfo.setTargetType(zbnm);
            videoInfo.setZzdx(bean.getMc());
            videoInfoMapper.updateByPrimaryKeySelective(videoInfo);
            System.out.println("targetJoinData_6");

        }
        if (dataType.equals(MediaEnum.IMAGE.getIndex())) {
            if (imageInfoMapper.selectCountBytargetXh(param.getZbnm(), param.getId()) >= maxJoinNum) {
                return "400,目标关联数据超过最大限制!";
            }
            TImageInfo imageInfo = new TImageInfo();
            imageInfo.setId(id);
            imageInfo.setTargetType(zbnm);
            imageInfo.setZzdx(bean.getMc());
            imageInfoMapper.updateByPrimaryKeySelective(imageInfo);
            System.out.println("targetJoinData_8");
        }
        System.out.println("targetJoinData_9end");
        return "200,关联成功";
    }


    @Transactional(rollbackFor = Exception.class)
    public String synTarget() {
        /**
         * 先获取到oracle库中所有的目标信息，
         * 删除dm库中的目标信息
         * 将数据插入到dm库中
         */
        List<NewTCodeTargetType> list = oracleTargetMapper.selectAll();
        targetMapper.deleteAll();
        for (NewTCodeTargetType newTCodeTargetType : list) {
            targetMapper.insert(newTCodeTargetType);
            System.out.println("synTarget_1");
        }
        System.out.println("synTarget_2end");
        return "同步成功";
    }

    public void onlyDeleteFile(String fileurl) {


        String fileUrl1 = fileurl;
        System.out.println("删除地址打印:" + fileUrl1);
        String dirUrl = fileUrl1.substring(0, fileUrl1.lastIndexOf("/"));
        cn.hutool.core.io.FileUtil.del(dirUrl);

    }

    /**
     * 0,文件类别
     * 1,国家
     * 2,侦照对象
     * 3,型号
     * @param files
     * @return
     * @throws IOException
     */
    public Object batchImport(List<MultipartFile> files) throws IOException, ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        for (MultipartFile file : files) {
            String fileRealUrl = uploadService.uploadImage(file);
            String fullName = file.getOriginalFilename();
            if (StringUtils.isBlank(fullName)){
                continue;
            }
            ArrayList<String> list = parseDirectory(fullName);
            String fileName = fullName.substring(fullName.lastIndexOf("/") + 1);
            //文件类别
//            String fileType = list.get(0);
            //国家
//            String counrty = list.get(1);
            //侦照对象
            String zzdx = list.get(2);
            //型号
//            String type = list.get(3);
            String[] split = fileName.split("-");
            /**
             * 名称中的字段是nm么?
             */
            String bdnm=split[0];
            String zdnm=split[1];
            String wqzbbh=split[2];
            String dateTime=split[3];
            NewTCodeTargetType target = targetMapper.getOneTargetByMC(zzdx);

            ImageParam imageParam = new ImageParam();
            TImageInfo tImageInfo = new TImageInfo();
            imageParam.setRealFileUrl(fileRealUrl);
            imageParam.setCategoryIds(null);
            imageParam.setFileName(fileName);
            imageParam.setUploadFileName(fileName);
            /**
             * 导入的是成果还是素材
             */
            imageParam.setIsProduct((byte) 1);
            imageParam.setTargetType(target.getZbnm());

            assignService.giveImageInfo(imageParam, tImageInfo);
            BeanUtils.copyProperties(imageParam, tImageInfo);
            tImageInfo.setBdnm(zdnm);
            tImageInfo.setWqzbbh(wqzbbh);
            tImageInfo.setZzdx(zzdx);
            tImageInfo.setShotDate(dateFormat.parse(dateTime));
            tImageInfo.setCreateDate(dateFormat.parse(dateTime));
            imageInfoMapper.insertSelective(tImageInfo);

            String categoryStr = StringUtils.join(list, "','");
            List<TCodeCategoryType> categoryTypes = categoryTypeMapper.getCategoryByMcStr("'"+categoryStr+"'");
            if (categoryTypes != null && categoryTypes.size() > 0) {
                for (TCodeCategoryType categoryType : categoryTypes) {
                    TQbCategoryConnection conn = new TQbCategoryConnection();
                    conn.setUserId(1L);
                    conn.setCategoryId(categoryType.getId().longValue());
                    conn.setMessageId(tImageInfo.getId());
                    conn.setConnectionType(MediaEnum.IMAGE.getIndex());
                    connectionMapper.insert(conn);
                }
            }
        }
        return "导入成功";
    }

    private ArrayList<String> parseDirectory(String name) {
        String[] split = name.split("/");
        return new ArrayList<>(Arrays.asList(split));
    }
//    private LinkedHashMap<String, String> parseDirectory(String name) {
//        LinkedHashMap<String, String> map = new LinkedHashMap<>();
//        map.put("文件类别", "");
//        map.put("国家", "");
//        map.put("侦照对象", "");
//        map.put("型号", "");
//        String[] split = name.split("/");
//        for (int i = 0; i < split.length - 1; i++) {
//            String keyByIndex = getKeyByIndex(map, i);
//            map.put(keyByIndex, split[i]);
//            System.out.println(keyByIndex);
//        }
//        return map;
//
//    }

    private static String getKeyByIndex(LinkedHashMap<String, String> map, int index) {
        return map.keySet().toArray()[index].toString();
    }

    public Object fixedMemo() {
        return fixMemoMapper.getAll();
    }



}
